#include <iostream>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;

void usage(char *argv[])
{
    cout << "please input like: " << argv[0] << " ip"
         << " port[1024+]" << endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        // 命令行参数不正确
        usage(argv);
        return 1;
    }

    uint16_t port = atoi(argv[2]);
    string ip = argv[1];
    int sockfd = 0;

    while (true)
    {
        int cnt = 5;
        bool isreconnect = false;
        // 创建socket
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            cout << "socket create failed" << endl;
            return 1;
        }

        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(port);
        inet_pton(AF_INET, ip.c_str(), &(server.sin_addr));

        // connect
        do
        {
            int c = connect(sockfd, (const sockaddr *)&server, sizeof(server));
            if (c < 0)
            {
                isreconnect = true;
                cnt--;
                cout << "connect failed, cnt:" << cnt << endl; 
                sleep(2);
            }
            else
            {
                isreconnect = false;
            }
        } while (cnt && isreconnect);

        if(cnt == 0)
        {
            cout << "user offonline" << endl;
            break;
        }

        string mess;
        cout << "client say# ";
        getline(cin, mess);
        ssize_t s = write(sockfd, mess.c_str(), mess.size());
        if (s < 0)
        {
            cerr << "write error..." << endl;
            continue;
        }

        char inbuffer[1024] = {0};
        ssize_t r = read(sockfd, inbuffer, sizeof(inbuffer));
        if (r > 0)
        {
            inbuffer[r] = 0;
            cout << inbuffer << endl;
        }
        close(sockfd);
    }

    return 0;
}